package com.chao.ioc.factory;

import com.chao.ioc.bean.BeanDefinition;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author : Rookie
 * @description : 资源加载器
 * @date : 2023/10/4
 */
public class ResourceLoader {

    /**
     * 将properties中的bean名称和对应的类名 加载成BeanDefinition 并返回bean定义map
     * @return
     */
    public static Map<String, BeanDefinition> loadResource() {
        Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
        Properties properties = new Properties();
        InputStream inputStream = null;
        try {
            inputStream = ResourceLoader.class.getClassLoader().getResourceAsStream("bean.properties");
            properties.load(inputStream);

            for (String key : properties.stringPropertyNames()) {
                String className = properties.getProperty(key);
                Class<?> beanClass = Class.forName(className);
                BeanDefinition beanDefinition = new BeanDefinition();
                beanDefinition.setBeanName(key);
                beanDefinition.setBeanClass(beanClass);
                beanDefinitionMap.put(key, beanDefinition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return beanDefinitionMap;
    }
}
